<template>
  <view class="container" :style="appThemeStyle">
    <u-navbar
      :is-back="false"
      :background="{ backgroundColor: appTheme.mainBg }"
    >
      <view class="nav-wrap">
        <view class="sub-list">
          <view
            v-for="(item, index) in subList"
            :class="['sub-item', { active: curSub === index }]"
            :key="index"
            @click="onChangeSub(index)"
          >
            <text class="name">{{ item.name }}</text>
            <text class="circle" v-if="badgeCount.count > 0"></text>
          </view>
        </view>
        <view class="setting">
          <text class="iconfont icon-setting"  @click="handleSetting"></text>
        </view>
      </view>
    </u-navbar>
    <view class="main-header">
<!--      <u-search-->
<!--        placeholder="搜索聊天记录"-->
<!--        :show-action="false"-->
<!--        v-model="searchValue"-->
<!--        shape="square"-->
<!--        :disabled="true"-->
<!--        @search="onSearch"-->
<!--        @click="toMessage"-->
<!--      />-->
      <view class="tabs-wrap">
        <view class="core">
          <u-tabs
            :list="tabs"
            :is-scroll="true"
            name="channelName"
            v-model="selectChannelIndex"
            :duration="0.2"
            font-size="28"
            @change="onChangeTab"
          />
        </view>
        <view class="controls" @click.stop="handleOnlyUnread">{{ onlyUnread ? '全部' : '未读' }}</view>
      </view>
    </view>
    <view class="conversations" v-if="chatList.length">
      <view class="private-header">顾客消息<text v-if="badgeCount.privateCount">（{{ badgeCount.privateCount }}）</text></view>
      <view class="scroll-item" v-for="(chatItem, key) in chatList" :key="key">
        <view class="item-head">
          <view
              v-if="chatItem.type === imAction.IM_PRIVATE"
              class="iconfont head-icon"
              style="color: #1677FF"
          >&#xe6d8;</view>
          <view
              v-else-if="chatItem.type === imAction.IM_GROUP"
              class="iconfont head-icon"
              style="color: #00B42A"
          >&#xe6d7;</view>
        </view>
        <view class="scroll-item_info" @click="chat(chatItem)">
          <view class="item-info-top">
            <view class="item-info-top_name">
              <view class="oneline-hide">{{ chatItem.shopName || chatItem.shopId }}</view>
              <view
                v-if="formatChannel(chatItem.thirdChannelId)"
                :style="{ backgroundColor: formatChannel(chatItem.thirdChannelId)?.color || '' }"
                class="channel"
              >{{ formatChannel(chatItem.thirdChannelId)?.label || '' }}</view>
            </view>
            <view class="item-info-top_time">{{ formatTime(chatItem.lastMessage.sendTime) }}</view>
          </view>
          <view class="item-info-bottom">
            <view
                v-if="chatItem.lastMessage.status === imMessageStatus.SUCCESS
                  || chatItem.lastMessage.status === imMessageStatus.READ"
                class="item-info-top_content oneline-hide"
            >
              <text
                  v-if="formatSenderRole(chatItem.lastMessage.senderRole)"
                  :class="[{ 'unread-text': chatItem.lastMessage.status === imMessageStatus.SUCCESS }]"
              >[{{ formatSenderRole(chatItem.lastMessage.senderRole) }}消息]</text>
              <text v-if="chatItem.lastMessage.contentType === imMessageType.TEXT">{{ chatItem.lastMessage.content.text }}</text>
              <text v-else-if="chatItem.lastMessage.contentType === imMessageType.VIDEO">[视频消息]</text>
              <text v-else-if="chatItem.lastMessage.contentType === imMessageType.VOICE">[语音消息]</text>
              <text v-else-if="chatItem.lastMessage.contentType === imMessageType.IMAGE">[图片消息]</text>
              <text v-else-if="chatItem.lastMessage.contentType === imMessageType.GOODS">[商品卡片]</text>
              <text v-else-if="chatItem.lastMessage.contentType === imMessageType.ORDER">[订单卡片]</text>
              <text v-else>[暂不支持的消息]</text>
            </view>
            <view
                v-else-if="chatItem.lastMessage.status === imMessageStatus.REVOKE
                && formatSenderRole(chatItem.lastMessage.senderRole)"
                class="item-info-top_content oneline-hide"
            >
              <text>{{formatSenderRole(chatItem.lastMessage.senderRole)}}撤回了一条消息</text>
            </view>
            <view
                v-if="chatItem.unreadCount"
                class="item-info-bottom_badge"
            >{{ chatItem.unreadCount > 99 ? '99+' : chatItem.unreadCount }}</view>
          </view>
        </view>
      </view>
    </view>
    <Empty url="empty-msg" tips="当前没有会话！" v-else/>
    <view class="placeholder"></view>
    <!-- 动态TabBar -->
    <TabBar/>
  </view>
</template>
<script>
import Empty from '@/components/empty'
import {formatTime} from '@/utils/util'
import { imAction, imMessageType, imSenderRole, imMessageStatus } from "@/common/constant/im";
import store from '@/store'
import im from '@/core/mixins/im'
import bigDecimal from "@/utils/bigDecimal";
import ChannelTypeEnum from "@/common/enum/channelType"
import TabBar from '@/components/tabbar'

export default {
  name: "index",
  mixins: [im],
  components: {TabBar, Empty },
  data() {
    return {
      imAction,
      imMessageType,
      imSenderRole,
      imMessageStatus,
      formatTime,
      searchValue: '',
      curSub: 0,
      subList: [{ name: '消息' }],
      selectThirdChannelId: -1,
      selectChannelIndex: 0,
      onlyUnread: false,
      badgeCount: {
        privateCount: 0,
        groupCount: 0,
        count: 0
      }
    }
  },
  computed: {
    channels() {
      return store.getters.channels
    },
    allChannels() {
      return store.getters.allChannels
    },
    messageUser() {
      return store.getters.messageUser
    },
    messageMaxId() {
      return store.getters.messageMaxId
    },
    unreadMessageIds() {
      return store.getters.unreadMessageIds
    },
    masterShopUnReadMessageIds() {
      return store.getters.masterShopUnReadMessageIds
    },
    userInfo() {
      return store.getters.userInfo
    },
    previewChannels() {
      const { shopId } = this.userInfo
      if (shopId === '0') {
        return (this.allChannels || []).filter(item =>
            item.channelId === ChannelTypeEnum.MT.value
            || item.channelId === ChannelTypeEnum.ELE.value
        ).map(item => {
          const { channelId, channelName } = item
          return { thirdChannelId: channelId, channelName }
        })
      }
      return (this.channels || []).filter(item =>
          item.thirdChannelId === ChannelTypeEnum.MT.value
          || item.thirdChannelId === ChannelTypeEnum.ELE.value
      )
    },
    tenant() {
      return store.getters.tenant
    },
    tabs() {
      return [{ thirdChannelId: -1, channelName: '全部' }, ...this.previewChannels ]
    },
    /**
     * 全部下的会话列表
     */
    allChatList() {
      const tenantId = this.tenant?.id
      // 边界情况的处理
      if (!tenantId || !this.messageUser[tenantId] || !this.userInfo?.id) {
        return []
      }
      // 存储最终结果
      let result = []
      const tenantMessage = this.messageUser[tenantId]
      const { shopId } = this.userInfo
      // 总部的情况
      if (shopId === '0') {
        const chatList = []
        for (const messageGroupKey in tenantMessage) {
          chatList.push(...tenantMessage[messageGroupKey])
        }
        result = chatList
      } else {
        // 单门店的情况
        const privateChatList = tenantMessage[`${imAction.IM_PRIVATE}_${shopId}`] || []
        const groupChatList = tenantMessage[`${imAction.IM_GROUP}_${shopId}`] || []
        result = [...privateChatList, ...groupChatList]
      }
      result.forEach(item => {
        // 统计未读数量
        item.unreadCount = this.getUnReadCount(item.messageList)
      })
      // 按照时间倒序排列
      result = result.sort((a, b) => {
        return bigDecimal.subtract(b.lastMessage.sendTime, a.lastMessage.sendTime)
      })
      return result
    },
    /**
     * 获取指定渠道下的会话列表
     */
    thirdChannelChatList() {
      return function (thirdChannelId) {
        if (this.allChatList?.length) {
          return this.allChatList.filter(item => item.thirdChannelId === thirdChannelId)
        }
        return []
      }
    },
    /**
     * 最终展示的会话列表
     */
    chatList() {
      let result = []
      if (this.selectThirdChannelId === -1) {
        result = this.allChatList
      } else {
        result = this.thirdChannelChatList(this.selectThirdChannelId)
      }
      if (this.onlyUnread) {
        return result.reduce((pre, cur) => {
          if (cur.unreadCount > 0) {
            pre.push(cur)
          }
          return pre
        }, [])
      }
      return result
    }
  },
  watch: {
    allChatList: {
      handler(nVal, oVal) {
        this.getTabbarUnreadCount()
      },
      immediate: true,
      deep: true
    }
  },
  onShow() {
    this.getTabbarUnreadCount()
  },
  onReady() {
    uni.$on('refreshIM', () => {
      this.onChangeTab(0)
    })
  },
  onUnload() {
    uni.$off('refreshIM')
  },
  methods: {
    /**
     * 获取tabbar未读消息数量
     */
    getTabbarUnreadCount() {
      const tenantId = this.tenant?.id
      const { shopId } = this.userInfo
      if (!tenantId || !shopId) {
        return
      }
      let privateCount = 0
      let groupCount = 0
      if (shopId === '0') {
        privateCount = this.masterShopUnReadMessageIds?.[tenantId]?.[imAction.IM_PRIVATE]?.length || 0
        groupCount = this.masterShopUnReadMessageIds?.[tenantId]?.[imAction.IM_GROUP]?.length || 0
      } else {
        privateCount = bigDecimal.add(privateCount, this.unreadMessageIds[tenantId]?.[`${imAction.IM_PRIVATE}_${shopId}`]?.length || 0)
        groupCount = bigDecimal.add(groupCount, this.unreadMessageIds[tenantId]?.[`${imAction.IM_GROUP}_${shopId}`]?.length || 0)
      }
      const count = bigDecimal.add(privateCount, groupCount)
      this.badgeCount = { privateCount, groupCount, count }
      // 更新角标
      store.commit('SET_TABBAR_BADGE', count)
    },
    onChangeSub(index) {
      this.curSub = index
    },
    onChangeTab(index) {
      this.selectChannelIndex = index
      this.selectThirdChannelId = this.tabs[index].thirdChannelId
    },
    /**
     * 获取未读消息数量
     */
    getUnReadCount(messageList) {
      if (!messageList?.length) {
        return 0
      }
      return messageList.filter(item =>
          item?.status === imMessageStatus.SUCCESS
          && item.senderRole !== imSenderRole.MERCHANT).length
    },
    /**
     * 根据渠道ID反查渠道信息
     * @param channelId
     */
    formatChannel(channelId) {
      if (this.allChannels?.length) {
        const channel = this.allChannels.find(item => item.channelId === channelId)
        if (channel) {
          const { abbreviation, color } = channel
          return {
            label: abbreviation,
            color
          }
        }
        return null
      }
      return null
    },
    /**
     * 跳转聊天页面
     * @param chatItem
     */
    chat(chatItem) {
      const { type, shopName, shopId, thirdChannelId, friendId, orderId, channelOrderNo } = chatItem
      const path = type === imAction.IM_PRIVATE ? 'private-chat' : 'group-chat'
      if (type === imAction.IM_GROUP) {
        return
      }
      // 跳转之前进行消息的排序
      chatItem.messageList = chatItem.messageList.sort((a, b) => {
        return a.sendTime - b.sendTime
      })
      // 处理跳转参数
      const channelInfo = this.formatChannel(thirdChannelId)
      store.commit('SET_PRIVATE_CHAT_PARAMS', {
        shopName: shopName || shopId,
        channelLabel: channelInfo?.label || '',
        channelColor: channelInfo?.color || '',
        channelId: thirdChannelId,
        friendId,
        shopId,
        orderId,
        channelOrderNo
      })
      this.$navTo(`messagepages/message/${path}`)
    },
    /**
     * 跳转设置页
     */
    handleSetting() {
      this.$navTo('messagepages/setting/index')
    },
    /**
     * 仅展示未读消息
     */
    handleOnlyUnread() {
      this.onlyUnread = !this.onlyUnread
    }
  }
}
</script>

<style scoped lang="scss">
.container {

  .nav-wrap {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .sub-list {
      width: 160rpx;
      margin-left: 40rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .sub-item {
        font-size: 28rpx;
        color: #ffffff;
        opacity: 0.6;
        position: relative;

        &.active {
          font-size: 34rpx;
          font-weight: bold;
          opacity: 1
        }

        .circle {
          position: absolute;
          top: -3rpx;
          width: 12rpx;
          height: 12rpx;
          border-radius: 50%;
          background: red;
          display: inline-block;
        }
      }
    }

    .setting {
      margin-right: 20rpx;
      font-size: 36rpx;
      color: #ffffff;
    }
  }

  .main-header {
    padding: 16rpx 24rpx 0;
    background: #fff;

    .tabs-wrap {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .core {
        width: 85%;
      }

      .controls {
        background: #F0F7FF;
        font-size: 24rpx;
        width: 96rpx;
        height: 58rpx;
        line-height: 58rpx;
        text-align: center;
        border-radius: 8rpx;
        color: #2D71FD;
      }
    }
  }

  .conversations {
    overflow-x: hidden;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    border-radius: 16rpx;
    background-color: white;
    margin: 16rpx 24rpx;
    width: calc(100% - 48rpx);

    .private-header {
      color: #333333;
      font-weight: 500;
      font-size: 30rpx;
      line-height: 42rpx;
      padding: 32rpx 24rpx 0 24rpx;
    }

    .scroll-item {
      display: flex;
      padding: 32rpx 24rpx 0 24rpx;

      .item-head {
        position: relative;
        flex-shrink: 0;
        margin-right: 20rpx;

        .head-icon {
          font-size: 84rpx;
        }
      }

      .scroll-item_info {
        flex: 1;
        box-sizing: border-box;
        border-bottom: 1px solid #EFEFEF;
        min-width: 0;

        .item-info-top {
          display: flex;
          align-items: center;

          .item-info-top_name {
            flex: 1;
            display: flex;
            align-items: center;

            .oneline-hide {
              min-width: 0;
              font-size: 28rpx;
              color: #333333;
              font-weight: 500;
            }
            .channel {
              width: 32rpx;
              height: 32rpx;
              margin-left: 8rpx;
              border-radius: 4rpx;
              line-height: 32rpx;
              text-align: center;
              font-size: 20rpx;
              color: white;
            }
          }

          .item-info-top_time {
            font-size: 24rpx;
            color: #BFBFBF;
            flex-shrink: 0;
          }
        }

        .item-info-bottom {
          margin-top: 8rpx;
          display: flex;
          align-items: center;
          margin-bottom: 32rpx;

          .item-info-top_content {
            font-size: 26rpx;
            color: #8C8C8C;
            flex: 1;
            min-width: 0;

            .unread-text {
              color: #2D71FD;
            }
          }
          .item-info-bottom_badge {
            flex-shrink: 0;
            margin-left: 12rpx;
            padding: 4rpx 10rpx;
            background-color: #F53F3F;
            border-radius: 24rpx;
            color: #ffffff;
            font-size: 20rpx;
            line-height: 20rpx;
            font-weight: 500;
          }
        }
      }
    }
  }

  .placeholder {
    width: 1px;
    height: 12px;
  }

  /* 隐藏滚动条 */
  ::-webkit-scrollbar {
    width: 0;
    height: 0;
    color: transparent;
  }
}
</style>
